<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // // 用对象记录添加的事件
        // let eventObj = {}
        // function addEvent(eventName, event) {
        //     if (eventObj[eventName] == undefined) {
        //         eventObj[eventName] = []
        //     }
        //     eventObj[eventName].push(event)
        // }
        // addEvent('event1', fn1)
        // function fn1() {
        //     console.log('这是事件1的fn1')
        // }
        // addEvent('event1', fn2)
        // function fn2() {
        //     console.log('这是事件1的fn2')
        // }
        // addEvent('event2', fn3)
        // function fn3() {
        //     console.log('这是事件2的fn3')
        // }
        // addEvent('event2', fn4)
        // function fn4() {
        //     console.log('这是事件2的fn4')
        // }

        // function trigger(eventName) {
        //     eventObj[eventName].forEach(function(item) {
        //         item()
        //     })
        // }
        // trigger('event1')
        // trigger('event2')

        // 改造成类
        class EventObj {
            constructor() {
                this.eventObj = {}
            }
            addEvent(eventName, event) {
                if (this.eventObj[eventName] == undefined) {
                    this.eventObj[eventName] = []
                }
                this.eventObj[eventName].push(event)
            }
            trigger(eventName) {
                if (typeof this.eventObj[eventName] !== "undefined") {
                    this.eventObj[eventName].forEach(function (item) {
                        item()
                    })
                } else {
                    throw Errow('参数传递错误')
                }
            }
        }

        let a = new EventObj()
        a.addEvent('event1', function () {
            console.log('这是事件1的fn1')
        })
        a.addEvent('event1', function () {
            console.log('这是事件1的fn2')
        })
        a.addEvent('event2', function () {
            console.log('这是事件2的fn3')
        })
        a.addEvent('event2', function () {
            console.log('这是事件2的fn4')
        })
        console.log(a)
        a.trigger('event1')
        a.trigger('event2')




    </script>
</body>

</html>